import { Request, Response, NextFunction } from 'express';
import jwt, { JwtPayload } from 'jsonwebtoken';

// 扩展Express的Request类型以支持user属性
declare global {
  namespace Express {
    interface Request {
      user?: any; // 使用any类型避免类型冲突，实际数据结构由运行时决定
    }
  }
}

export const authenticate = (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization as string | undefined;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw new Error('Missing or invalid token');
    }
    
    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'default_secret') as JwtPayload & { userId?: string; role?: string };
    
    // 确保decoded包含必要的用户信息
    if (!decoded.userId || !decoded.role) {
      throw new Error('Invalid token payload');
    }
    
    req.user = {
      userId: decoded.userId,
      role: decoded.role
    };
    
    next();
  } catch (error) {
    console.error('Authentication error:', error);
    res.status(401).json({ 
      message: 'Authentication failed', 
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
};